package com.flute.framework.search.highlight;

import com.flute.tools.util.StringUtil;

/**
 * 标红实现类
 * 
 * @author Dave
 * 
 */
public class SimpleMark implements IMarkstyle {

	/**
	 * 标红的开始和结束的html样式
	 */
	private String headFont = "<font color=\"red\">";
	private String tailFont = "</font>";

	public SimpleMark() {

	}

	public SimpleMark(String head, String tail) {
		headFont = head;
		tailFont = tail;
	}

	/**
	 * 将标红的结果组装成value
	 * 
	 * @see com.flute.Flute.mark.IMarkstyle#markString(com.flute.Flute.mark.MarkPosition[])
	 */
	@Override
	public String markString(MarkPosition[] ks) {
		if (ks.length > 0) {
			String source = ks[0].getSource();
			StringBuilder value = new StringBuilder("");
			int end = 0;
			for (int i = 0; i < ks.length; i++) {
				value = value.append(value.toString()).append(
						source.substring(end, ks[i].getStart())).append(
						getMarkedString(source.substring(ks[i].getStart(),
								ks[i].getEnd() + 1)));
				end = ks[i].getEnd() + 1;
			}

			if (end < source.length()) {
				value = value.append(value.toString()).append(
						source.substring(end, source.length()));
			}

			return value.toString();
		}

		return "";
	}

	/**
	 * @param s
	 *            标红的关键词
	 * @return 标红的开始和结束的html结果
	 */
	private String getMarkedString(String s) {
		if (StringUtil.isNullOrEmpty(headFont)
				&& StringUtil.isNullOrEmpty(tailFont)) {
			headFont = "<font color=\"red\">";
			tailFont = "</font>";
		}

		return headFont + s + tailFont;
	}
}
